package com.beasts.antpage.sh.service;

import com.beasts.antpage.sh.entity.Layout;
import com.beasts.antpage.sh.repository.LayoutRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Locker
 * @date 20/04/2018 11:02 AM
 * @since 1.0
 */
@Service
public class LayoutServiceImpl implements ILayoutService {

    @Autowired
    private LayoutRepository layoutRepository;

    @Override
    public List<Layout> findAll(String name) {
        return layoutRepository.findAll();
    }

    @Override
    public List<String> findAllLayoutName() {
        List<String> namesList = new ArrayList<String>();

        List<Layout> allLayouts = this.findAll("");
        for (Layout l : allLayouts) {
            namesList.add(l.getId() + "," + l.getName());
        }

        return namesList;
    }

    @Override
    public String findLayoutHtml(String pageId) {
        Layout layout = layoutRepository.findAllById(pageId);
        return layout.getHtml();
    }

    @Override
    public String deleteLayoutHtml(String pageId) {
        layoutRepository.delete(pageId);
        return "ok";
    }

    @Override
    public String saveLayout(String pageId, String name, String html,String editHtml) {
        Layout layout = new Layout();
        try {
            if(StringUtils.isNotEmpty(pageId)){
                layout.setId(pageId);
            }else{
                Date currentTime = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
                String dateString = formatter.format(currentTime);
                layout.setId(dateString);
            }

//            layout.setId((new Date()).getTime());

            layout.setName(name);
            layout.setHtml(html);
            layout.setEditHtml(editHtml);
            layoutRepository.save(layout);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return pageId;
    }

    @Override
    public Layout findLayoutById(String pageId) {
        return layoutRepository.findOne(pageId);
    }
}
